import { articleApi } from '@/api/articles'
import { collectionApi } from '@/api/collections'

const state = {
  articles: [],
  currentArticle: null,
  loading: false,
  searchKeyword: '',
  filterStatus: 'all', // all, draft, published
  // 新增合集相关状态
  collections: [],
  filterCollection: 'all', // all, '', tech, life, travel, etc.
  loadingCollections: false
}

const getters = {
  filteredArticles: (state) => {
    let articles = state.articles
    
    // 搜索过滤
    if (state.searchKeyword) {
      articles = articles.filter(article => 
        article.title.toLowerCase().includes(state.searchKeyword.toLowerCase()) ||
        article.content.toLowerCase().includes(state.searchKeyword.toLowerCase())
      )
    }
    
    // 状态过滤
    if (state.filterStatus !== 'all') {
      articles = articles.filter(article => article.status === state.filterStatus)
    }
    
    // 新增：合集过滤
    if (state.filterCollection !== 'all') {
      articles = articles.filter(article => {
        // 如果筛选“未分类”，显示 collection 为空或不存在的文章
        if (state.filterCollection === '') {
          return !article.collection || article.collection === ''
        }
        // 否则按具体合集ID过滤
        return article.collection === state.filterCollection
      })
    }
    
    return articles.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
  },
  
  articleById: (state) => (id) => {
    return state.articles.find(article => article.id === id)
  },
  
  // 新增：合集相关 getters
  collectionById: (state) => (id) => {
    return state.collections.find(collection => collection.id === id)
  },
  
  getCollectionName: (state, getters) => (collectionId) => {
    if (!collectionId || collectionId === '') {
      return '未分类'
    }
    const collection = getters.collectionById(collectionId)
    return collection ? collection.name : '未知合集'
  },
  
  getCollectionColor: (state, getters) => (collectionId) => {
    if (!collectionId || collectionId === '') {
      return '#C0C4CC'
    }
    const collection = getters.collectionById(collectionId)
    return collection ? collection.color : '#C0C4CC'
  },
  
  articlesInCollection: (state) => (collectionId) => {
    if (collectionId === 'all') {
      return state.articles
    }
    if (collectionId === '') {
      return state.articles.filter(article => !article.collection || article.collection === '')
    }
    return state.articles.filter(article => article.collection === collectionId)
  },
  
  collectionsWithCount: (state, getters) => {
    return state.collections.map(collection => ({
      ...collection,
      count: getters.articlesInCollection(collection.id).length
    }))
  }
}

const mutations = {
  SET_ARTICLES(state, articles) {
    state.articles = articles
  },
  
  SET_CURRENT_ARTICLE(state, article) {
    state.currentArticle = article
  },
  
  ADD_ARTICLE(state, article) {
    state.articles.unshift(article)
  },
  
  UPDATE_ARTICLE(state, updatedArticle) {
    const index = state.articles.findIndex(article => article.id === updatedArticle.id)
    if (index !== -1) {
      state.articles.splice(index, 1, updatedArticle)
    }
  },
  
  DELETE_ARTICLE(state, articleId) {
    state.articles = state.articles.filter(article => article.id !== articleId)
  },
  
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  
  SET_SEARCH_KEYWORD(state, keyword) {
    state.searchKeyword = keyword
  },
  
  SET_FILTER_STATUS(state, status) {
    state.filterStatus = status
  },
  
  // 新增：合集相关 mutations
  SET_COLLECTIONS(state, collections) {
    state.collections = collections
  },
  
  SET_FILTER_COLLECTION(state, collectionId) {
    state.filterCollection = collectionId
  },
  
  SET_LOADING_COLLECTIONS(state, loading) {
    state.loadingCollections = loading
  },
  
  ADD_COLLECTION(state, collection) {
    state.collections.push(collection)
  },
  
  UPDATE_COLLECTION(state, updatedCollection) {
    const index = state.collections.findIndex(c => c.id === updatedCollection.id)
    if (index !== -1) {
      state.collections.splice(index, 1, updatedCollection)
    }
  },
  
  DELETE_COLLECTION(state, collectionId) {
    state.collections = state.collections.filter(c => c.id !== collectionId)
  }
}

const actions = {
  async loadArticles({ commit }) {
    commit('SET_LOADING', true)
    try {
      const articles = await articleApi.getAll()
      commit('SET_ARTICLES', articles)
    } catch (error) {
      console.error('加载文章失败:', error)
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  async createArticle({ commit }, articleData) {
    try {
      const article = await articleApi.create(articleData)
      commit('ADD_ARTICLE', article)
      return article
    } catch (error) {
      console.error('创建文章失败:', error)
      throw error
    }
  },
  
  async updateArticle({ commit }, { id, data }) {
    try {
      const article = await articleApi.update(id, data)
      commit('UPDATE_ARTICLE', article)
      return article
    } catch (error) {
      console.error('更新文章失败:', error)
      throw error
    }
  },
  
  async deleteArticle({ commit }, articleId) {
    try {
      await articleApi.delete(articleId)
      commit('DELETE_ARTICLE', articleId)
    } catch (error) {
      console.error('删除文章失败:', error)
      throw error
    }
  },
  
  async getArticle({ commit, getters }, articleId) {
    // 先从本地查找
    let article = getters.articleById(articleId)
    if (!article) {
      // 如果本地没有，从API获取
      try {
        article = await articleApi.getById(articleId)
      } catch (error) {
        console.error('获取文章失败:', error)
        throw error
      }
    }
    commit('SET_CURRENT_ARTICLE', article)
    return article
  },
  
  // 新增：合集相关 actions
  async loadCollections({ commit }) {
    commit('SET_LOADING_COLLECTIONS', true)
    try {
      const collections = await collectionApi.getAll()
      commit('SET_COLLECTIONS', collections)
    } catch (error) {
      console.error('加载合集失败:', error)
    } finally {
      commit('SET_LOADING_COLLECTIONS', false)
    }
  },
  
  setCollectionFilter({ commit }, collectionId) {
    commit('SET_FILTER_COLLECTION', collectionId)
  },
  
  setSearchKeyword({ commit }, keyword) {
    commit('SET_SEARCH_KEYWORD', keyword)
  },
  
  setStatusFilter({ commit }, status) {
    commit('SET_FILTER_STATUS', status)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}